import {getOrderList} from "@src/api/deposit";
import dayjs from "dayjs";
import router from "@src/router";

Component({
  behaviors: [router.routerBehavior],
  data: {
    dayList: [],
    pageNum: 1,
    pageSize: 10,
    hasNextPage: false,
    loading: false
  },
  methods: {
    onLogin() {
      this.fetchData();
    },
    /*上下拉刷新*/
    onPullDownRefresh() {
      this.setData({
        pageNum: 1,
        pageSize: 10,
        dayList: []
      })
      this.fetchData();
    },
    onReachBottom() {
      console.info("onReachBottom")
      if (this.data.hasNextPage) {
        this.setData({pageNum: this.data.pageNum + 1});
        this.fetchData();
      }
    },
    fetchData() {
      /*暂停刷新*/
      let data = {
        page: this.data.pageNum,
        pageSize: this.data.pageSize
      };
      this.setData({loading: true})
      getOrderList(data).then(res => {
        wx.stopPullDownRefresh();
        if (res.code === 0) {
          let list = res.data.list;
          list.map(value => {
            if (value.status === 0) {
              value.statusTitle = "已寄存"
            } else if (value.status === 1) {
              value.statusTitle = "已支取"
            } else if (value.status === 2) {
              value.statusTitle = "已过期"
            }
          })
          this.setData({hasNextPage: res.data.hasNextPage, loading: false})
          this.parseList(list);
        } else {
          this.setData({loading: false})
        }
      }).catch(() => {
        this.setData({loading: false})
      })
    },
    parseList(newList) {
      if (!newList || newList.length === 0) {
        return;
      }
      let dayMap = {}, lastDay = null, dayList = this.data.dayList;
      if (dayList.length > 0) {
        lastDay = dayList[dayList.length - 1].day;
      }
      let statusTitles = {0: "已寄存", 1: "已支取", 2: "已过期"};
      for (let order of newList) {
        order.statusTitle = statusTitles[order.status]
        let day = dayjs(order.createTime).format("YYYY-MM-DD");
        if (dayMap[day] === undefined) {
          dayMap[day] = [];
        }
        dayMap[day].push(order);
      }
      for (let day in dayMap) {
        if (lastDay !== null && day === lastDay) {
          dayList[dayList.length - 1].list.push(...dayMap[day])
        } else {
          dayList.push({day: day, list: dayMap[day]})
        }
      }
      this.setData({dayList: dayList})
    },
  }
})
